import { useTranslation } from "react-i18next";
import crc32 from "crc/crc32";

const translateKey = (key: string): string => {
  return `K${crc32(key).toString(16)}`;
};

const useTranslations = (): ((key: string, params?: any[]) => string) => {
  const { t } = useTranslation();

  const $t = (key: string, params?: any[]): string => {
    const hashKey = translateKey(key);
    let words = t(hashKey);

    if (words === hashKey) {
      words = key;
    }

    if (Array.isArray(params)) {
      const reg = /\((\d)\)/g;
      words = words.replace(reg, (a, b) => params[Number(b)] || a);
    }

    return words;
  };

  return $t;
};

export default useTranslations;
